<?php
// Just CRUD for entry categories
class Category_Manager extends Model {
	private $_current_blogger_id;
	
	function Category_Manager() {
		parent::Model();
		$this->_current_blogger_id = 0;
		$this->load->library('common');
	}
	
	function SetCurrentBloggerID($current_blogger_id) {
		$this->_current_blogger_id = $current_blogger_id;
	}
	
	function _check_blogger_id() {
		if($this->_current_blogger_id == 0) {
			throw new Exception('ERROR: Invalid Blogger-ID!');
		}
	}
	
	function AddCategory($cate_title, $cate_desc) {
		$this->_check_blogger_id();
		
		$parms = array(
			'title' => $cate_title,
			'blogger_id' => $this->_current_blogger_id,
			'description' => $cate_desc
		);
		$this->db->insert('nt_categories', $parms);
		$new_cate_id = $this->db->insert_id();
		return $new_cate_id;
	}
	
	function ModifyCategory($cate_id, $new_cate_title, $new_cate_desc) {
		$this->_check_blogger_id();
		
		$this->db->query('UPDATE `nt_categories` SET `title` = ?, `description` = ? WHERE `id` = ? AND `blogger_id` = ?', array($new_cate_title, $new_cate_desc, $cate_id, $this->_current_blogger_id));
		$this->db->query('UPDATE `nt_entries` SET `category_title` = ? WHERE `blogger_id` = ? AND `category_id` = ?', array($new_cate_title, $this->_current_blogger_id, $cate_id));
	}
	
	function RemoveCategory($cate_id) {
		$this->db->query('DELETE FROM `nt_categories` WHERE `id` = ? AND `blogger_id` = ?', array($cate_id, $this->_current_blogger_id));
		$this->db->query('UPDATE `nt_entries` SET `category_id` = 1, `category_title` = ? WHERE `category_id` = ? AND `blogger_id` = ?', array('未分类', $cate_id, $this->_current_blogger_id));
	}
	
	function GetCategory($cate_id) {
		$qry = $this->db->query('SELECT * FROM `nt_categories` WHERE `id` = ? AND `blogger_id` = ?', array($cate_id, $this->_current_blogger_id));
		return $qry->row();
	}
}
?>